<template>
  <n-card :bordered="false">
    <basic-table
      :title='title'
      :data='data'
      :row-key="rowKey"
      :columns='columns'
      ref='useTableRef'
    >
      <template #tableTitle>
        <n-space>
          <n-button type='info' @click='handleAdd(null)'>添加</n-button>
        </n-space>
      </template>      
    </basic-table>

    <n-modal
      v-model:show='showModal'
      :show-icon="false"
      style="width:650px"
      :title="modalTitle"
      preset="dialog">
      <n-form :model='form' ref='formRef'>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="上级菜单" path="username">
            <n-tree-select 
              :options='menuOption'
              label-field="menuName"
              key-field="id"
              v-model:value="form.parentId"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="上级菜单" path="menuType">
            <n-radio-group v-model:value="form.menuType" name="menuType">
              <n-space>
                <n-radio value="C">目录</n-radio>
                <n-radio value="M">菜单</n-radio>
                <n-radio value="B">按钮</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="菜单图标" path="icon" v-if="form.menuType!=='B'">
            <n-input v-model:value="form.icon" placeholder="请输入菜单图标" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="菜单名称" path="menuName">
            <n-input v-model:value="form.menuName" placeholder="请输入菜单名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="显示顺序" path="orderNum">
            <n-input v-model:value="form.orderNum" placeholder="请输入菜单名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="路由地址" path="path">
            <n-input v-model:value="form.path" placeholder="请输入路由地址，例如user" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="组件地址" path="component">
            <n-input v-model:value="form.component" placeholder="请输入菜单名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="权限标示" path="perms">
            <n-input v-model:value="form.perms" placeholder="请输入权限标识，例如system:user:add" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="是否显示" path="visible">
            <n-radio-group v-model:value="form.visible" name="status">
              <n-space>
                <n-radio
                  v-for='item in showHideOption'
                  :key='item.dictValue'
                  :value='item.dictValue'
                  :label='item.dictValue'>{{ item.dictLabel }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
        </n-grid>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click='() => (showModal=false)'>取消</n-button>
          <n-button @click='submitForm' :loading='btnLoading' type="info">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang='ts' setup>
  import { onMounted, ref, unref, reactive, getCurrentInstance, h, computed } from 'vue'
  import { list } from '@/api/commonApi'
  import { delMenu, listMenu, addMenu, updateMenu } from '@/api/system/menu'
  import OperateButton from '@/components/OperateButton/index.vue'
  import { BasicTable } from '@/components/Table'
  import { useStore } from 'vuex'

  const internalInstance: any = getCurrentInstance()
  const { handleTree, selectDictLabel, getDict, $dialog, $notification, $message } = internalInstance?.appContext.config.globalProperties
  const store = useStore()
  const showHideOption = ref([])

  const rowKey = (row: any) => row.id
  const columns = [{
    title: '菜单名称',
    key: 'menuName',
    width: 150
  }, {
    title: '图标',
    key: 'icon',
    width: 100
  }, {
    title: '序号',
    key: 'orderNum',
    width: 50
  }, {
    title: '权限',
    key: 'perms',
    width: 180
  }, {
    title: '组件路径',
    key: 'component',
    width: 180
  }, {
    title: '可见',
    key: 'visible',
    width: 50,
    render(row: any) {
      return selectDictLabel(showHideOption.value, row.visible)
    }
  }, {
    title: '创建日期',
    key: 'createTime',
    width: 150
  }, {
    title: '操作',
    key: 'operate',
    width: 160,
    render: function(row) {
      return h(OperateButton, {
        buttonList: [
          { title: '添加', type: 'info', size: 'small', onClick: () => handleAdd(row) },
          { title: '编辑', type: 'info', size: 'small', onClick: () => handleEdit(row) },
          { title: '删除', type: 'error', size: 'small', onClick: () => handleDelete(row) }
        ]
      })
    }
  }]
  const data = ref([])
  const loading = ref(false)
  const title = ref('菜单管理')
  const menuOption = ref<any>([])

  const baseUrl = '/system/menu'
  async function getMenuList () {
    loading.value = true
    const res = await list(baseUrl, null)
    data.value = handleTree(res.data)
    loading.value = false
  }
  
  /** 新增时，表单的默认值 */
  const defaultForm = {
    status: '1'
  }
  /** 新增、编辑表单 */
  const form = ref({} as any)
  /** 表单标题 */
  const modalTitle = ref('添加菜单')
  /** modal是否显示 */
  const showModal = ref(false)
  /** modal的提交按钮loading */
  const btnLoading = ref(false)

  function getMenuTree() {
    listMenu().then(res => {
      menuOption.value = []
      const menu = { id: '0', menuName: '主目录', children: [] }
      menu.children = handleTree(res.data)
      menuOption.value.push(menu)
    })
  }

  function handleAdd(row: any) {
    form.value = defaultForm
    if(row) {
      form.value.parentId = row.id
    }
    modalTitle.value = '添加菜单'
    showModal.value = true
    form.value = defaultForm
    getMenuTree()
  }

  function handleEdit(row: any) {
    console.log('handleEdit',row)
  }

  async function submitForm() {
    btnLoading.value = true
    const id = unref(form).id
    if(id) {

    } else {
      await addMenu(unref(form))
      $message.success('添加成功')
    }

    showModal.value = false
    btnLoading.value = false
  }

  function handleDelete(row: any) {
    console.log('handleDelete',row)

    $dialog.error({
      title: '提示',
      content: `确定要删除【${row.menuName}】吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        delMenu(row.id).then(res => {
          $notification.success({
            content: '删除成功',
            duration: 1500
          })
          getMenuList()
        })
      },
      onNegativeClick: () => {}
    })
  }

    
  onMounted(() => {
    getDict('is_visible').then(res => {
      showHideOption.value = res.data
      getMenuList()
    })
  })


</script>